package com.SmartCare.service.impl.apiLog;

import com.SmartCare.common.dto.apiLog.ApiUserTop;
import com.SmartCare.common.enums.Constants;
import com.SmartCare.common.exception.ServiceException;
import com.SmartCare.pojo.role.User;
import com.SmartCare.service.role.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.SmartCare.common.Result;
import com.SmartCare.common.dto.apiLog.ApiLogDTO;
import com.SmartCare.common.dto.apiLog.ApiManageDTO;
import com.SmartCare.mapper.apiLog.ApiLogMapper;
import com.SmartCare.pojo.apiLog.ApiLog;
import com.SmartCare.service.apiLog.ApiLogService;
import com.SmartCare.utils.ApiLogsTransToDTO;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 接口调用日志表 服务实现类
 */
@Service
public class ApiLogServiceImpl extends ServiceImpl<ApiLogMapper, ApiLog> implements ApiLogService {

    @Resource
    private ApiLogsTransToDTO apiLogsTransToDTO;

    @Resource
    private UserService userService;

    @Override
    public Result query(String name) {
        //获取该养老院的所有日志信息
        List<ApiLog> list = list(new QueryWrapper<ApiLog>().eq("ch_name", name));
        List<ApiLogDTO> result = apiLogsTransToDTO.trans(list);
        //整理数据
        ApiManageDTO apiManageDTO = new ApiManageDTO(result);
        return Result.success(apiManageDTO);
    }

    @Override
    public Result search(Integer pageNum, Integer pageSize, String keyword, String type, String name) {
        // 分页
        IPage<ApiLog> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<ApiLog> qw = new QueryWrapper<>();
        qw.eq("ch_name", name);

        if ("user_id".equals(type)) {
            qw.apply("user_id IN (SELECT user_id FROM user WHERE name LIKE {0})", "%" + keyword + "%");
        } else {
            // 如果type不是"user_id"，进行模糊查询
            qw.like(type, keyword);
        }

        qw.orderByDesc("create_date");
        IPage<ApiLog> page = page(iPage, qw);

        // 获取符合条件的ApiLog记录

        List<ApiLog> apiLogList = page.getRecords();

        // 将ApiLog记录转换为ApiLogDTO
        List<ApiLogDTO> dtoList = apiLogsTransToDTO.trans(apiLogList);

        // 创建新的IPage用于存放转换后的信息
        IPage<ApiLogDTO> dtoPage = new Page<>();
        dtoPage.setRecords(dtoList);
        dtoPage.setTotal(page.getTotal());
        dtoPage.setCurrent(page.getCurrent());
        dtoPage.setSize(page.getSize());
        dtoPage.setPages(page.getPages());

        // 返回成功结果
        return Result.success(dtoPage);
    }

    @Override
    public void export(HttpServletResponse response, String name) {

        //查询药品数据
        List<ApiLog> logs = list(new QueryWrapper<ApiLog>().eq("ch_name", name));
        List<ApiLogDTO> list = apiLogsTransToDTO.trans(logs);

        //创建一个新的Excel工作簿
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet("ApiLogs");

            //创建标题行
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("接口名称");
            headerRow.createCell(1).setCellValue("接口描述");
            headerRow.createCell(2).setCellValue("调用次数");
            headerRow.createCell(3).setCellValue("调用用户");
            headerRow.createCell(4).setCellValue("调用日期");

            //填充数据行
            int rowNum = 1;
            for (ApiLogDTO log : list) {
                Row dataRow = sheet.createRow(rowNum++);
                if (log.getApiName() != null) {
                    dataRow.createCell(0).setCellValue(log.getApiName());
                }
                if (log.getDescFunction() != null) {
                    dataRow.createCell(1).setCellValue(log.getDescFunction());
                }
                if (log.getTimes() != null) {
                    dataRow.createCell(2).setCellValue(log.getTimes());
                }
                if (log.getUser() != null) {
                    dataRow.createCell(3).setCellValue(log.getUser().getName());
                }
                if (log.getCreateDate() != null) {
                    dataRow.createCell(4).setCellValue(log.getCreateDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
            }
            //设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=export.xlsx");

            // 将工作簿内容写入响应输出流
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result queryTopLogs(String careHomeName, String startTime, String endTime) {
        // 获取养老院的所有日志
        QueryWrapper<ApiLog> qw = new QueryWrapper<>();
        qw.eq("ch_name", careHomeName);
        qw.between("create_date", startTime, endTime);
        List<ApiLog> list = list(qw);

        // 使用Java Stream API 进行统计
        Map<String, Integer> moduleCallCounts = list.stream()
                .collect(Collectors.groupingBy(ApiLog::getModule, Collectors.summingInt(ApiLog::getTimes)));
        return Result.success(moduleCallCounts);
    }

    @Override
    public Result topByUser(String careHomeName, String startTime, String endTime) {
        // 获取养老院的所有日志
        QueryWrapper<ApiLog> qw = new QueryWrapper<>();
        qw.eq("ch_name", careHomeName);
        qw.between("create_date", startTime, endTime);
        List<ApiLog> list = list(qw);
        // 根据用户进行分类
        Map<Long, Integer> moduleCallCounts = list.stream()
                .collect(Collectors.groupingBy(ApiLog::getUserId, Collectors.summingInt(ApiLog::getTimes)));
        // 排序后返回
        List<ApiUserTop> result = new ArrayList<>();
        for (Long userId : moduleCallCounts.keySet()) {
            QueryWrapper<User> uqw = new QueryWrapper<>();
            uqw.select("user_id, name, nickname, avatar_url");
            uqw.eq("user_id", userId);
            User byId = userService.getOne(uqw);
            if (byId == null) {
//                throw new ServiceException(Constants.CODE_400, "用户信息未找到");
            } else {
                result.add(ApiUserTop.builder()
                        .times(moduleCallCounts.get(userId))
                        .user(byId)
                        .build());
            }
        }
        result.sort(Comparator.comparing(ApiUserTop::getTimes));
        return Result.success(result);
    }
}
